package com.kuang.demo.service;

import com.github.pagehelper.PageHelper;
import com.kuang.demo.bean.GoodsBean.GoodsBO.*;
import com.kuang.demo.bean.GoodsBean.GoodsVO.FileUpLoadGoodsPicVO;
import com.kuang.demo.bean.GoodsBean.GoodsVO.GoodsCommetVO;
import com.kuang.demo.bean.GoodsBean.GoodsVO.GoodsDetailVO;
import com.kuang.demo.bean.GoodsBean.GoodsVO.GoodsListVO;
import com.kuang.demo.mapper.*;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class GoodsServiceImpl implements GoodsService {
    @Autowired
    GoodsMapper goodsMapper;
    @Autowired
    AddGoodsMapper addGoodsMapper;
    @Autowired
    GoodsAttributeMapper goodsAttributeMapper;
    @Autowired
    GoodsProductMapper goodsProductMapper;
    @Autowired
    GoodsSpecificationMapper goodsSpecificationMapper;
    @Autowired
    GoodsCommentMapper goodsCommentMapper;
    @Autowired
    StorageMapper storageMapper;
    @Value("${25mall.pic.upload}")
    String picUploadPath;


    public GoodsListVO goodsList0(GoodsListVO goodsListVO, long page, int limit, String sort, String order) {
        goodsListVO.setErrno(0);
        goodsListVO.setErrmsg("成功");
        GoodsListVO.DataBean dataBean = new GoodsListVO.DataBean();
        dataBean.setTotal(goodsMapper.selectGoodsTotalById());
        PageHelper.startPage((int) page, limit);
        List<GoodsListVO.DataBean.ItemsBean> items = goodsMapper.selectGoodsBySortAndOrder(sort, order);
        dataBean.setItems(items);
        goodsListVO.setData(dataBean);
        return goodsListVO;
    }


    public GoodsListVO goodsList1(GoodsListVO goodsListVO, int page, int limit, String sort, String order, String goodsSn) {
        goodsListVO.setErrno(0);
        goodsListVO.setErrmsg("成功");
        GoodsListVO.DataBean dataBean = new GoodsListVO.DataBean();
        dataBean.setTotal(goodsMapper.selectGoodsTotalById());
        PageHelper.startPage( page, limit);
        List<GoodsListVO.DataBean.ItemsBean> items = goodsMapper.selectGoodsBySortAndOrderAndGoodsSn(sort, order,goodsSn);
        dataBean.setItems(items);
        goodsListVO.setData(dataBean);
        return goodsListVO;
    }

    public GoodsListVO goodsList2(GoodsListVO goodsListVO, int page, int limit, String sort, String order, String name) {
        goodsListVO.setErrno(0);
        goodsListVO.setErrmsg("成功");
        GoodsListVO.DataBean dataBean = new GoodsListVO.DataBean();
        dataBean.setTotal(goodsMapper.selectGoodsTotalById());
        PageHelper.startPage( page, limit);
        List<GoodsListVO.DataBean.ItemsBean> items = goodsMapper.selectGoodsBySortAndOrderAndName(sort, order,name);
        dataBean.setItems(items);
        goodsListVO.setData(dataBean);
        return goodsListVO;
    }

    @Override
    public GoodsListVO goodsList(GoodsListVO goodsListVO, int page, int limit, String sort, String order, String goodsSn, String name) {
        if(null==goodsSn&&null==name){
            goodsList0(goodsListVO,page,limit,sort,order);
        }
        if(null==goodsSn&&!name.equals(null))
        {
            goodsList1(goodsListVO,page,limit,sort,order,name);
        }
        if(null==name&&!goodsSn.equals(null))
        {
            goodsList1(goodsListVO,page,limit,sort,order,goodsSn);
        }
        goodsListVO.setErrno(0);
        goodsListVO.setErrmsg("成功");
        GoodsListVO.DataBean dataBean = new GoodsListVO.DataBean();
        dataBean.setTotal(goodsMapper.selectGoodsTotalById());
        PageHelper.startPage( page, limit);
        List<GoodsListVO.DataBean.ItemsBean> items = goodsMapper.selectGoodsBySortAndOrderAndGoodsSnAndName(sort, order,goodsSn,name);
        dataBean.setItems(items);
        goodsListVO.setData(dataBean);
        return goodsListVO;
    }

    @Override
    public CatAndBrandBO catAndBrand(CatAndBrandBO catAndBrandBO) {
        catAndBrandBO.setErrno(0);
        catAndBrandBO.setErrmsg("成功");
        CatAndBrandBO.DataBean dataBean = new CatAndBrandBO.DataBean();
        List<CatAndBrandBO.DataBean.CategoryListBean> categoryListBeans = goodsMapper.selectCategoryFatherById();
        for (CatAndBrandBO.DataBean.CategoryListBean listBean : categoryListBeans) {
            int id = listBean.getValue();
            List<CatAndBrandBO.DataBean.CategoryListBean.ChildrenBean> childrenBeans = goodsMapper.selectCategoryChirldrenById(id);
            listBean.setChildren(childrenBeans);
        }
        dataBean.setCategoryList(categoryListBeans);
        dataBean.setBrandList(goodsMapper.selectBrandList());
        catAndBrandBO.setData(dataBean);
        return catAndBrandBO;
    }

    @Override
    public void addGoods(GoodsAddList goodsAddList) {
        GoodsAddList.GoodsBean goods = goodsAddList.getGoods();
        List<GoodsAddList.SpecificationsBean> specifications = goodsAddList.getSpecifications();
        List<GoodsAddList.ProductsBean> products = goodsAddList.getProducts();
        List<GoodsAddList.AttributesBean> attributes = goodsAddList.getAttributes();
        AddGoods addGoods = new AddGoods();
        addGoodsMapperMsg(goods, addGoods);
        GoodsSpecification goodsSpecification = new GoodsSpecification();
        GoodsProduct goodsProduct = new GoodsProduct();
        GoodsAttribute goodsAttribute = new GoodsAttribute();
        addGoodsMapper.insert(addGoods);
        /**
         * 添加goodsSn
         *
         */
        int i = Integer.parseInt(goods.getGoodsSn());
        insertGoodsSpecification(specifications, goodsSpecification, i);
        insertGoodsProducts(products, goodsProduct, i);
        insertGoodsAttribute(attributes, goodsAttribute, i);
    }

    @Override
    public void deleteGoodsList(AddGoods addGoods) {
        Integer id = addGoods.getId();
        AddGoodsExample addGoodsExample = new AddGoodsExample();
        addGoodsExample.createCriteria().andIdEqualTo(id);
        addGoodsMapper.deleteByExample(addGoodsExample);
    }

    @Override
    public GoodsDetailVO selectGoodsDetailById(int id) {
        GoodsDetailVO goodsDetailVO = new GoodsDetailVO();
        GoodsDetailVO.GoodsBean goodsBean = new GoodsDetailVO.GoodsBean();
        AddGoodsExample addGoodsExample = new AddGoodsExample();
        addGoodsExample.createCriteria().andIdEqualTo(id);

        goodsBean = goodsMapper.selectGoodsById(id);
        goodsDetailVO.setGoods(goodsBean);

        int categoryId = goodsMapper.selectcategoryIdById(id);
        List<Integer> categoryIds = goodsMapper.selectcategoryIdByCategoryId(categoryId);
        goodsDetailVO.setCategoryIds(categoryIds);

        List<GoodsDetailVO.SpecificationsBean> specificationsBeans =
                goodsMapper.selectSpecificationsBeanById(id);
        goodsDetailVO.setSpecifications(specificationsBeans);

        List<GoodsDetailVO.AttributesBean> attributesBeans =
                goodsMapper.selectAttributesBeans(id);
        goodsDetailVO.setAttributes(attributesBeans);

        List<GoodsDetailVO.ProductsBean> productsBeans =
                goodsMapper.selectProductsBeanById(id);
        goodsDetailVO.setProducts(productsBeans);

        return goodsDetailVO;
    }

    @Override
    public void updateGoodsDetail(GoodsDetailVO goodsDetailVO) {
        AddGoods addGoods = new AddGoods();
        int i = Integer.parseInt(goodsDetailVO.getGoods().getGoodsSn());
        GoodsSpecification goodsSpecification = new GoodsSpecification();
        GoodsProduct goodsProduct = new GoodsProduct();
        GoodsAttribute goodsAttribute = new GoodsAttribute();

        updateGoodsMsg(goodsDetailVO, addGoods, i);

        updateGoodsSpecMsg(goodsDetailVO, i, goodsSpecification);

        updateGoodsAttriMsg(goodsDetailVO, i, goodsAttribute);

        updateGoodsProductMsg(goodsDetailVO, i, goodsProduct);
    }

    /**
     * 废弃
     * @param page
     * @param limit
     * @param sort
     * @param order
     * @return
     */
//    @Override
//    public GoodsCommetVO CommentList(int page, int limit, String sort, String order) {
//        GoodsCommetVO goodsCommetVO = new GoodsCommetVO();
//        int total = goodsCommentMapper.selectTotalById();
//        goodsCommetVO.setTotal(total);
//        PageHelper.startPage(page, limit);
//        List<GoodsCommetVO.ItemsBean> items = goodsCommentMapper.selectGoodsCommentsBySortAndOrder(sort, order);
//        goodsCommetVO.setItems(items);
//        return goodsCommetVO;
//    }

    @Override
    public GoodsCommetVO CommentList(int page, int limit, String sort, String order, int userId, int valueId) {
        GoodsCommetVO goodsCommetVO = new GoodsCommetVO();
        int total = goodsCommentMapper.selectTotalById();
        goodsCommetVO.setTotal(total);
        PageHelper.startPage(page, limit);
        List<GoodsCommetVO.ItemsBean> items = goodsCommentMapper.selectGoodsCommentsBySortAndOrder(sort, order,userId,valueId);
        goodsCommetVO.setItems(items);
        return goodsCommetVO;
    }

    @Override
    public void deleteGoodsCommentById(int id) {
        goodsCommentMapper.deleteGoodsCommentById(id);
    }

    @SneakyThrows
    @Override
    public FileUpLoadGoodsPicVO createPic(String url, MultipartFile file) {
        UUID uuid = UUID.randomUUID();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        String time = dateFormat.format(new Date());
        int size = (int) file.getSize();
        String contentType = file.getContentType();
        String name = file.getOriginalFilename();
        FileUpLoadGoodsPicVO dataBean = new FileUpLoadGoodsPicVO();
        dataBean.setKey(uuid + ".jpg");
        dataBean.setName(name);
        dataBean.setSize(size);
        dataBean.setAddTime(time);
        dataBean.setUpdateTime(time);
        dataBean.setType(contentType);
        File file1 = new File(picUploadPath, uuid + ".jpg");
        System.out.println(file1);
        dataBean.setUrl(url + uuid + ".jpg");
        storageMapper.insertFileUpPic(dataBean.getName(),dataBean.getType(), dataBean.getSize(), dataBean.getUrl(), dataBean.getAddTime(), dataBean.getUpdateTime(), dataBean.getKey());
        file.transferTo(file1);
        return dataBean;
    }


    private void updateGoodsProductMsg(GoodsDetailVO goodsDetailVO, int i, GoodsProduct goodsProduct) {
        List<GoodsDetailVO.ProductsBean> productsBeans = goodsDetailVO.getProducts();
        for (GoodsDetailVO.ProductsBean productsBean : productsBeans) {
            goodsProduct.setId(productsBean.getId());
            goodsProduct.setSpecifications(productsBean.getSpecifications());
            BigDecimal price = BigDecimal.valueOf(productsBean.getPrice());
            goodsProduct.setPrice(price);
            goodsProduct.setNumber(productsBean.getNumber());
            goodsProduct.setUrl(productsBean.getUrl());
            goodsProduct.setGoodsId(i);
            GoodsProductExample goodsProductExample = new GoodsProductExample();
            goodsProductExample.createCriteria().andGoodsIdEqualTo(i);
            goodsProductMapper.updateByExample(goodsProduct, goodsProductExample);
        }
    }

    private void updateGoodsAttriMsg(GoodsDetailVO goodsDetailVO, int i, GoodsAttribute goodsAttribute) {
        List<GoodsDetailVO.AttributesBean> attributesBeans = goodsDetailVO.getAttributes();
        for (GoodsDetailVO.AttributesBean attributesBean : attributesBeans) {
            goodsAttribute.setAttribute(attributesBean.getAttribute());
            goodsAttribute.setValue(attributesBean.getValue());
            goodsAttribute.setGoodsId(i);
            GoodsAttributeExample goodsAttributeExample = new GoodsAttributeExample();
            goodsAttributeExample.createCriteria().andGoodsIdEqualTo(i);
            goodsAttributeMapper.updateByExample(goodsAttribute, goodsAttributeExample);
        }
    }

    private void updateGoodsSpecMsg(GoodsDetailVO goodsDetailVO, int i, GoodsSpecification goodsSpecification) {
        List<GoodsDetailVO.SpecificationsBean> specifications = goodsDetailVO.getSpecifications();
        for (GoodsDetailVO.SpecificationsBean specification : specifications) {
            goodsSpecification.setSpecification(specification.getSpecification());
            goodsSpecification.setPicUrl(specification.getPicUrl());
            goodsSpecification.setValue(specification.getValue());
            goodsSpecification.setGoodsId(i);
            GoodsSpecificationExample goodsSpecificationExample = new GoodsSpecificationExample();
            goodsSpecificationExample.createCriteria().andGoodsIdEqualTo(i);
            goodsSpecificationMapper.updateByExample(goodsSpecification, goodsSpecificationExample);
        }
    }

    private void updateGoodsMsg(GoodsDetailVO goodsDetailVO, AddGoods addGoods, int i) {
        addGoods.setPicUrl(goodsDetailVO.getGoods().getPicUrl());
        addGoods.setGallery(goodsDetailVO.getGoods().getGallery());
        addGoods.setBrandId(goodsDetailVO.getGoods().getBrandId());
        addGoods.setUnit(goodsDetailVO.getGoods().getUnit());
        addGoods.setKeywords(goodsDetailVO.getGoods().getKeywords());
        addGoods.setCategoryId(goodsDetailVO.getGoods().getCategoryId());
        addGoods.setBrief(goodsDetailVO.getGoods().getBrief());
        addGoods.setDetail(goodsDetailVO.getGoods().getDetail());
        addGoods.setGoodsSn(goodsDetailVO.getGoods().getGoodsSn());
        addGoods.setName(goodsDetailVO.getGoods().getName());
        BigDecimal counterPrice = BigDecimal.valueOf(goodsDetailVO.getGoods().getCounterPrice());
        addGoods.setCounterPrice(counterPrice);
        BigDecimal retailPrice = BigDecimal.valueOf(goodsDetailVO.getGoods().getRetailPrice());
        addGoods.setRetailPrice(retailPrice);
        addGoods.setIsNew(goodsDetailVO.getGoods().isIsNew());
        addGoods.setIsHot(goodsDetailVO.getGoods().isIsHot());
        addGoods.setIsOnSale(goodsDetailVO.getGoods().isIsOnSale());
        AddGoodsExample addGoodsExample = new AddGoodsExample();
        addGoodsExample.createCriteria().andIdEqualTo(i);
        addGoodsMapper.updateByExample(addGoods, addGoodsExample);
    }


    private void insertGoodsAttribute(List<GoodsAddList.AttributesBean> attributes, GoodsAttribute goodsAttribute, int i) {
        for (GoodsAddList.AttributesBean attribute : attributes) {
            goodsAttribute.setAttribute(attribute.getAttribute());
            goodsAttribute.setValue(attribute.getValue());
            goodsAttribute.setGoodsId(i);
        }
    }

    private void insertGoodsProducts(List<GoodsAddList.ProductsBean> products, GoodsProduct goodsProduct, int i) {
        for (GoodsAddList.ProductsBean product : products) {
            goodsProduct.setId(product.getId());
            goodsProduct.setSpecifications(product.getSpecifications());
            goodsProduct.setPrice(product.getPrice());
            goodsProduct.setNumber(product.getNumber());
            goodsProduct.setUrl(product.getUrl());
            goodsProduct.setGoodsId(i);
        }
    }

    private void insertGoodsSpecification(List<GoodsAddList.SpecificationsBean> specifications, GoodsSpecification goodsSpecification, int i) {
        for (GoodsAddList.SpecificationsBean specification : specifications) {
            goodsSpecification.setSpecification(specification.getSpecification());
            goodsSpecification.setPicUrl(specification.getPicUrl());
            goodsSpecification.setValue(specification.getValue());
            goodsSpecification.setGoodsId(i);
            goodsSpecificationMapper.insert(goodsSpecification);
        }
    }

    private void addGoodsMapperMsg(GoodsAddList.GoodsBean goods, AddGoods addGoods) {
        addGoods.setPicUrl(goods.getPicUrl());
        addGoods.setGallery(goods.getGallery());
        addGoods.setBrandId(goods.getBrandId());
        addGoods.setUnit(goods.getUnit());
        addGoods.setKeywords(goods.getKeywords());
        addGoods.setCategoryId(goods.getCategoryId());
        addGoods.setBrief(goods.getBrief());
        addGoods.setDetail(goods.getDetail());
        addGoods.setGoodsSn(goods.getGoodsSn());
        addGoods.setName(goods.getName());
        addGoods.setCounterPrice(goods.getCounterPrice());
        addGoods.setRetailPrice(goods.getRetailPrice());
        addGoods.setIsNew(goods.isNew());
        addGoods.setIsHot(goods.isHot());
        addGoods.setIsOnSale(goods.isOnSale());
    }
}
